package com.wz.jiangsu.service.es.serviceImpl;

import cn.hutool.json.JSONUtil;
import com.wz.jiangsu.bean.vo.resp.PageResult;
import com.wz.jiangsu.bean.vo.resp.R;
import com.wz.jiangsu.bean.vo.show.DealWithEvent;
import com.wz.jiangsu.service.es.ESDealEventService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: wz
 * @author: wangzhou
 * @create: 2024-11-12 19:46
 * @description:
 **/
@Slf4j
@Service
public class ESDealEventServiceImpl implements ESDealEventService {

    @Autowired
    private RestHighLevelClient client;


    @Override
    public R<PageResult<DealWithEvent>> findByUUid(String uuid , String index) {
        SearchResponse response;
        SearchRequest request = new SearchRequest(index);
        request.source().query(QueryBuilders.termQuery("uuid",uuid));
        List<DealWithEvent> dto = new ArrayList<>();

        try {
            response= client.search(request, RequestOptions.DEFAULT);
            dto = Arrays.stream(response.getHits().getHits()).map(x -> {
                String sourceAsString = x.getSourceAsString();
                log.info("hit 转换后的字符串是:{}", sourceAsString);
                return JSONUtil.toBean(sourceAsString, DealWithEvent.class);
            }).collect(Collectors.toList());
            log.info("response 信息:{}",response.getClusters());
        } catch (IOException e) {
            log.error("发起查询请求出现异常:{}",e.getMessage());
            return R.error("发起查询请求出现异常");
        }

        PageResult<DealWithEvent> pageResult = PageResult.getPageResult(dto, response.getHits().getTotalHits());


        return R.success(pageResult);
    }
}
